package com.yan_jiu_sheng.LeetCodeHot100.AC;

/**
 * https://leetcode.cn/problems/add-two-numbers/description/?envType=study-plan-v2&envId=top-100-liked
 * 通过
 *
 * @author yulongTian
 * @create 2024-05-30 14:34
 */
public class Test28 {
    public static void main(String[] args) {

    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    private ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = l1;
        if (l1.val == 0 && l1.next == null) {
            return l2;
        }
        if (l2.val == 0 && l2.next == null) {
            return l1;
        }

        int c = 0;

        // 4 5 6 7 8
        // 1 2 3
        ListNode pre = l1;
        while (true) {
            if (l1 == null || l2 == null) {
                if (l1 == null) {
                    l1 = l2;
                    pre.next = l1;
                }
                while (l1 != null) {
                    int temp = l1.val;
                    l1.val = (c + temp) % 10;
                    c = (c + temp) / 10;
                    pre = l1;
                    l1 = l1.next;
                }
                if (c > 0) {
                    ListNode temp = new ListNode(c);
                    temp.next = null;
                    pre.next = temp;
                }
                break;
            }
            int temp = l1.val + l2.val;
            l1.val = (c + temp) % 10;
            c = (c + temp) / 10;
            pre = l1;
            l1 = l1.next;
            l2 = l2.next;
        }
        return res;
    }

}
